 package com.quo.controller;

import java.awt.Font;
import java.io.ByteArrayOutputStream;



import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.quo.annotation.Permission;
import com.quo.dto.ProductDto;
import com.quo.dto.ProductsDto;
import com.quo.entity.*;
import com.quo.service.ProductService;
import com.quo.service.QuoteService;
import com.quo.utils.DownloadUtils;
import com.quo.utils.ExcelImportUtil;
import com.quo.utils.ExcelWriter;
import com.quo.utils.Result;
import com.quo.utils.ResultCode;



/** 

* @author zhoumin
 * 

*/
@RestController("productController")
@RequestMapping(value="/api")
public class ProductController {

	@Autowired
	public ProductService pService;  
	
	@Autowired
	public QuoteService qService;

	//ChartPanel frame1;
	     //获取所有产品信息		
			  @GetMapping("/product")
			  public Result getProductList(){ 
				  
				  List<ProductsDto> plist =	pService.getProductList(); 
				  Result result=new Result(ResultCode.SUCCESS);
				  result.setData(plist);     
				  
				  return result;
			  
			  }
		  
		  //获取单个产品信息
		  @GetMapping("/product/{pid}")		
		  public Result getProduct(@PathVariable Long pid){ 
			  ProductDto product = pService.getProduct(pid);
			  Result result=new Result(ResultCode.SUCCESS);
			  result.setData(product);
			  return result;
		  
		  }
		  
		  //更新特定产品信息
		  @Permission(name = "product:edit")
		  @PutMapping("/product/{pid}")
		  public Result updateProduct(@PathVariable(value="pid") Long pid,@RequestBody Product product){ 
			  product.setPid(pid);		
			  pService.updateProduct(product);					
			  return new Result(ResultCode.SUCCESS);
		  
		  }		  		  
		  
		  //获取产品类型列表(产品编辑)
		
		  @GetMapping("/product-type-list-edit")		  
		  public Result getTypeList(){ 
			  List<ProductType> typeList = pService.getTypeList();
			  Result result=new Result(ResultCode.SUCCESS);
			  result.setData(typeList);
			  return result;
		  
		  }		
		  
		  //获取产品类型列表(添加新品)
		  @GetMapping("/product-type-list-add")		  
		  public Result getTypeListForNew(){ 
			  List<ProductType> typeList = pService.getTypeList();
			  Result result=new Result(ResultCode.SUCCESS);
			  result.setData(typeList);
			  return result;
		  
		  }	
		  
		//获取产品类型列表(シリーズ編集)
		  @GetMapping("/product-type-list-series-edit")		  
		  public Result getTypeListForSeries(){ 
			  List<ProductType> typeList = pService.getTypeList();
			  Result result=new Result(ResultCode.SUCCESS);
			  result.setData(typeList);
			  return result;
		  
		  }	
		  
		//获取产品类型列表(新規シリーズ)
		  @GetMapping("/product-type-list-series-add")		  
		  public Result getTypeListForNewSeries(){ 
			  List<ProductType> typeList = pService.getTypeList();
			  Result result=new Result(ResultCode.SUCCESS);
			  result.setData(typeList);
			  return result;
		  
		  }	
		  	  
		  
		  //获取产品系列列表(产品编辑)
		  @Permission(name = "product:edit")
		  @GetMapping("/product-series-list-edit")		 
		  public Result getSeriesListForEdit(){ 
			  List<ProductSeries2> seriesList = pService.getSeriesList();
			  System.out.println("AAAAAAAAAA"+seriesList);
			  Result result=new Result(ResultCode.SUCCESS);
			  result.setData(seriesList);
			  return result;
		  
		  }
		  
		  //获取产品系列列表(添加新品)
		  @GetMapping("/product-series-list-add")		  
		  public Result getSeriesListForNew(){ 
			  List<ProductSeries2> seriesList = pService.getSeriesList();
			  Result result=new Result(ResultCode.SUCCESS);
			  result.setData(seriesList);
			  return result;
		  
		  }
		  
		  
		  
		  //删除单个产品
			/*	  @RequestMapping(value="/product/{pid}",method=RequestMethod.DELETE)
				  @ResponseBody
				  public Result deleteProduct(@PathVariable(value="pid") Long pid){ 
					      pService.deleteProduct(pid);
					  return new Result(ResultCode.SUCCESS);
				  
				  }
				  */
		  @Permission(name = "product:delete")
		  @DeleteMapping("/product/{pid}")
		  public Result deleteProduct(@PathVariable(value="pid") Long pid){ 
			  
			  Long[] pids =	qService.getPidsByQuoteDetail();
			  if (Arrays.binarySearch(pids, pid) >=0) {
				  return new Result(ResultCode.NODEL);
			  }
			      pService.deleteProduct(pid);
			  return new Result(ResultCode.SUCCESS);
		  
		  }
		  
		  //删除多个产品
		  @PostMapping("/product-del")		  
		  public Result deleteProducts(@RequestBody Long[] pids){ 
			  
			  Long[] pidsOfQuote =	qService.getPidsByQuoteDetail();
			  for(Long pid:pids) {				 
			  	  if (Arrays.binarySearch(pidsOfQuote, pid) >=0) {
				  return new Result(ResultCode.NODEL);
			  }
			} 
			  		
				  pService.deleteProducts(pids);
				  
			  
			  return new Result(ResultCode.SUCCESS);
		  
		  }	

		  //添加单个产品
		  @Permission(name = "product:add")
		  @PostMapping("/product")
		  public Result addProduct(@RequestBody Product product){ 

			  	pService.addProduct(product);
			
				return new Result(ResultCode.SUCCESS);						  
		  
		  }		  


/**
 * author:韩宛廷
 * 产品导出
 * @param request
 * @param response
 * @throws IOException 
 */          
		    @RequestMapping(value="/product-export",method = RequestMethod.POST)
		    public void ProductExport(@RequestBody Long[] pids, HttpServletRequest request, HttpServletResponse response) {
		    	String[] arrays= {"产品编号","产品名称","产品类型名称","产品系列名称","价格","库存","耳机连接方式","耳机接口","降噪","重低音","防水功能","麦克风","包装清单"};
		 
				 response.setContentType("application/vnd.ms-excel"); 
				response.setHeader("Content-disposition", "attachment;filename=Product-"+System.currentTimeMillis()+".xlsx");
				List<ProductExport> proList =	pService.getByPids(pids);
		        System.out.println(proList);
				ExcelWriter<ProductExport> ew = new ExcelWriter<>();
				XSSFWorkbook workbook = ew.getWorkbook(proList, "产品信息", ProductExport.class,arrays);
				ServletOutputStream outputStream = null;
				try {
					outputStream=response.getOutputStream();
					workbook.write(outputStream);
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally {
					try {
						workbook.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					try {
						outputStream.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
		    }
		    
		    
//		    @RequestMapping(value="/product-export",method = RequestMethod.POST)
//		    public void ProductExport(@RequestBody Long[] pids, HttpServletRequest request, HttpServletResponse response) throws IOException {
//	    	 response.setContentType("application/octet-stream"); 
//					response.setHeader("Content-disposition", "attachment;filename=Product-"+System.currentTimeMillis()+".xlsx");
//					List<ProductExport> proList =	pService.getByPids(pids);
//					ProductExcelExporter exporter = new ProductExcelExporter(proList);
//					exporter.export(response);
//		    }
		    

		    @RequestMapping(value = "/products/template", method = RequestMethod.GET)
		    public void download(HttpServletResponse response) throws Exception {
		  
		        //构造Excel
		        //创建工作簿
		    	XSSFWorkbook wb = new XSSFWorkbook();
		        //构造sheet
		        Sheet sheet = wb.createSheet();
		        
		      //处理第一行
		        String [] templates1 = "必須,必須,必須,必須,必須,必須,必須,必須,必須,必須".split(",");
		        
		    	CellStyle style1 = wb.createCellStyle();
		    	XSSFFont font1 = wb.createFont();
		    	font1.setFontName("Yu Gothic UI");
				font1.setBold(false);
				font1.setFontHeight(11);
				style1.setFont(font1);
				style1.setAlignment(HorizontalAlignment.CENTER);
		        Row row0 = sheet.createRow(0);
		
		        int templateIndex1=0;
		        
		        for (int j = 0; j < templates1.length; j++) {

		        	  Cell cell = row0.createCell(templateIndex1++);
			          cell.setCellValue(templates1[j]);

//					sheet.autoSizeColumn(j);
//					int currentColumnWidth = sheet.getColumnWidth(j);
//					sheet.setColumnWidth(j, (currentColumnWidth + 1000));
					cell.setCellStyle(style1);

				}
		      //处理第二行
		        String [] templates2= "文字,半角数字(必ず存在する番号),整数,文字,文字,「あり」と「なし」のみ,「あり」と「なし」のみ,文字,「あり」と「なし」のみ,50文字以内".split(",");
		        
		    	CellStyle style2 = wb.createCellStyle();
		    	XSSFFont font2 = wb.createFont();
		    	font2.setFontName("Yu Gothic UI");
				font2.setBold(false);
				font2.setFontHeight(11);
				style2.setFont(font2);
				style2.setAlignment(HorizontalAlignment.CENTER);
		        Row row1 = sheet.createRow(1);
		
		        int templateIndex2=0;
		        
		        for (int x = 0; x < templates2.length; x++) {

		        	  Cell cell = row1.createCell(templateIndex2++);
			          cell.setCellValue(templates2[x]);

//					sheet.autoSizeColumn(x);
//					int currentColumnWidth = sheet.getColumnWidth(x);
//					sheet.setColumnWidth(x, (currentColumnWidth + 500));
					cell.setCellStyle(style2);
				}
		        
		  
		      //处理第三行
		        //标题
		        String [] titles = "製品名,シリーズID,単価,接続性,インタフェース,ノイキャン,重低音,防水,マイク通話,付属".split(",");
		        CellStyle Headstyle = wb.createCellStyle();
		        XSSFFont Headfont = wb.createFont();
				Headfont.setBold(true);
				Headfont.setFontHeight(11);
				Headfont.setFontName("Yu Gothic UI");
				Headstyle.setFont(Headfont);
				Headstyle.setAlignment(HorizontalAlignment.CENTER);
		      
		        //处理标题
		        //创建行
		        Row row2 = sheet.createRow(2);
		
		        int titleIndex=0;
		        for (int i = 0; i < titles.length; i++) {
		        	Cell cell = row2.createCell(titleIndex++);
		            cell.setCellValue(titles[i]);
//					sheet.autoSizeColumn(i);
//					int currentColumnWidth = sheet.getColumnWidth(i);
//					sheet.setColumnWidth(i, (currentColumnWidth + 500));
				cell.setCellStyle(Headstyle);
				}
                
		        for (int i = 0; i < 10; i++) {
//					sheet.autoSizeColumn(i);
//					int currentColumnWidth = sheet.getColumnWidth(i);
//					sheet.setColumnWidth(i, (currentColumnWidth + 500));
					sheet.autoSizeColumn(i);//先設定自動列寬 
					sheet.setColumnWidth(i, sheet.getColumnWidth(i)*17/10);
				}

	
		        
		        //3.完成下载
		        ByteArrayOutputStream os = new ByteArrayOutputStream();
		        wb.write(os);
		        new DownloadUtils().download(os,response,"产品表.xlsx");
		    }
		    
		    
		    /**
		     * 导入Excel，添加产品
		     *  文件上传
		     */
		    @RequestMapping(value="/products",method = RequestMethod.POST)
		    @ResponseBody
		    public Result importProducts(@RequestParam(name="file") MultipartFile file)  {
//		        //1.解析Excel
//		        //1.1.根据Excel文件创建工作簿
//		        Workbook wb = new XSSFWorkbook(file.getInputStream());
//		        //1.2.获取Sheet
//		        Sheet sheet = wb.getSheetAt(0);//参数：索引
//		        //1.3.获取Sheet中的每一行，和每一个单元格
//		        //2.获取用户数据列表
//		        List<ProductReport> list = new ArrayList<>();
//		        System.out.println(sheet.getLastRowNum());
//		        for (int rowNum =2; rowNum<= sheet.getLastRowNum() ;rowNum ++) {
//		            Row row = sheet.getRow(rowNum);//根据索引获取每一个行
//		            Object [] values = new Object[row.getLastCellNum()];
//		            for(int cellNum=0;cellNum< row.getLastCellNum(); cellNum ++) {
//		                Cell cell = row.getCell(cellNum);
//		                Object value = getCellValue(cell);
//		                values[cellNum] = value;
//		            }
//		            ProductReport pro2 = new ProductReport(values);
//		            list.add(pro2);
//		  
//		        }
//		        pService.saves(list);
//				return new Result(ResultCode.SUCCESS);
		    	Result result = new Result();
		        List<ProductReport> list;
				try {
					list = new ExcelImportUtil(ProductReport.class).readExcel(file.getInputStream(), 3, 0);
				} catch (Exception e) {
					result = new Result(ResultCode.FAIL);
					result.setMessage("入力されたフォーマットが正しくありません");
					return result;
				}
		        //3.批量保存用户
				try {
		        pService.saves(list);
		        return new Result(ResultCode.SUCCESS);
				} catch (Exception e) {
					result = new Result(ResultCode.FAIL);
					result.setMessage("入力されたフォーマットが正しくありません");
					return result;
				}
		       
		    }

		    public static Object getCellValue(Cell cell) {
		        //1.获取到单元格的属性类型
		        CellType cellType = cell.getCellType();
		        //2.根据单元格数据类型获取数据
		        Object value = null;
		        switch (cellType) {
		            case STRING:
		                value = cell.getStringCellValue();
		                break;
		            case BOOLEAN:
		                value = cell.getBooleanCellValue();
		                break;
		            case NUMERIC:
		                if(DateUtil.isCellDateFormatted(cell)) {
		                    //日期格式
		                    value = cell.getDateCellValue();
		                }else{
		                    //数字
		                    value = cell.getNumericCellValue();
		                }
		                break;
		            case FORMULA: //公式
		                value = cell.getCellFormula();
		                break;
		            default:
		                break;
		        }
		        return value;
		    }

}
